<?php
require_once('lib/cassandra/pandra/config.php');

class CassandraConnection {

	private static $_instance;
	private $_client;
	const DEFAULT_CONNECTION_NAME = 'default';
	const DEFAULT_CONNECTION_HOST = '127.0.0.1';
	const DEFAULT_CONNECTION_PORT = 9160;

	private function __construct($host = null, $port = null) {

		$host = isset($host) ? $host : self::DEFAULT_CONNECTION_HOST;
		$port = isset($port) ? $port : self::DEFAULT_CONNECTION_PORT;
		// create default named connection
		PandraCore::connect(self::DEFAULT_CONNECTION_NAME, $host, null, $port);


		// Setting reading and writing modes
		PandraCore::setReadMode(PandraCore::MODE_RANDOM);
		PandraCore::setWriteMode(PandraCore::MODE_ROUND);

		// get active CassandraClient (Thrift)
		$this->_client = PandraCore::getClient();

		// Set global consistency level
		PandraCore::setConsistency(cassandra_ConsistencyLevel::ONE);
	}

	public static function singleton($host = null, $port = null)
    {
        if (!isset(self::$_instance)) {
            $c = __CLASS__;
            self::$_instance = new $c($host, $port);
        }

        return self::$_instance;
    }

    public function getClient() {
    	return $this->_client;
    }

	public function __clone()
    {
        trigger_error('Connection object cannot be cloned.', E_USER_ERROR);
    }

	function __destruct() {
		// disconnect from every cluster cluster
		PandraCore::disconnectAll();
	}
}